
// pages/comment/comment.js
const api = require('../../utils/api');

Component({
    properties:{
        targetType: {
            //1:美食 2:景点 3:活动 4.路线 7.分享
            type: Number,
        },
        targetId: {
            type: Number,
            observer(newVal) {
                this.loadComments();
            }
        }
    },

    data:{
        comments: null,
        pageNum: 1,
        pageSize: 10,
        commentContent: null,
        likedCommentIds: new Set(),
        like: true,
        totalPages: 1,
        likedCommentIds: [], // 改用数组存储已点赞评论ID（可序列化）
    },

    //组件方法
    methods: {
        loadComments() {
            const { targetType, targetId } = this.properties;
            const { pageNum, pageSize, likedCommentIds } = this.data;
            
            api.comment.getCommentList(pageNum, pageSize, {
              targetType: targetType,
              targetId: targetId
            }).then(res => {
              const comments = res.records || res.list || res || [];
              // 匹配本地点赞状态：根据likedCommentIds更新评论的like字段
              const commentsWithLike = comments.map(comment => ({
                ...comment,
                // 核心：判断评论ID是否在本地已点赞数组中
                like: likedCommentIds.includes(comment.id)
              }));
              this.setData({
                comments: commentsWithLike
              });
            }).catch(err => {
              console.error('加载评论失败：', err);
            });
          },

        loadLikedComments() {
            const { pageNum, pageSize, likedCommentIds } = this.data;
            console.log('开始查询了！！！！！！！！');
            // 分页查询用户赞过的评论
            const targetType = 7
            api.like.getUserLikes(pageNum,pageSize,targetType).then(res =>{
                console.log('获取到的已点赞资源：',res);
            });
            
            
        },

        
        onCommentInput(e) {
            this.setData({
                commentContent: e.detail.value
            });
        },

        submitComment(){
            const {targetType, targetId} = this.properties;
            const {commentContent} = this.data;
            api.comment.addComment({
                targetType: targetType,
                targetId: targetId,
                content: commentContent
            }).then(res =>{
                wx.showToast({
                  title: '评论成功',
                })
                this.setData({ 
                    commentContent: '',
                    comments:null,
                    pageNum: 1
                });
                this.loadComments();
            }).catch(err => {
                console.error('评论失败',err);
            })
        },

        getLike(e) {
            const commentId = e.currentTarget.dataset.id;
            const { comments, likedCommentIds } = this.data;
            const targetType = 8; // 评论的targetType
            const commentIndex = comments.findIndex(item => item.id === commentId);
            
            if (commentIndex === -1) return;
          
            const currentComment = comments[commentIndex];
            const newIsLike = !currentComment.like; // 切换点赞状态
          
            // 调用接口更新后端状态
            api.like.changeLike(commentId, newIsLike, targetType).then(res => {
              // 1. 更新评论列表的点赞状态和数量
              const newComments = [...comments];
              newComments[commentIndex].like = newIsLike;
              newComments[commentIndex].likes = newIsLike 
                ? currentComment.likes + 1 
                : currentComment.likes - 1;
          
              // 2. 更新本地已点赞ID数组
              const newLikedIds = [...likedCommentIds];
              if (newIsLike) {
                // 点赞：添加ID（避免重复）
                if (!newLikedIds.includes(commentId)) {
                  newLikedIds.push(commentId);
                }
              } else {
                // 取消点赞：移除ID
                const idIndex = newLikedIds.indexOf(commentId);
                if (idIndex !== -1) {
                  newLikedIds.splice(idIndex, 1);
                }
              }
          
              // 3. 同步更新数据和本地缓存
              this.setData({
                comments: newComments,
                likedCommentIds: newLikedIds
              }, () => {
                // 持久化存储到本地缓存
                wx.setStorageSync('likedCommentIds', newLikedIds);
              });
          
              wx.showToast({
                title: newIsLike ? '点赞成功' : '取消点赞',
              });
            }).catch(err => {
              console.error('点赞失败：', err);
              wx.showToast({
                title: '操作失败',
                icon: 'none'
              });
            });
          },

    },

    lifetimes: {
        attached() {
            // 从本地缓存读取已点赞评论ID
            const storedLikedIds = wx.getStorageSync('likedCommentIds') || [];
            this.setData({
              likedCommentIds: storedLikedIds
            }, () => {
              // 如果已有targetId，初始化评论列表
              if (this.properties.targetId) {
                this.loadComments();
              }
            });
          }
    },

   // 修改onReachBottom方法，实现分页加载
onReachBottom() {
    const { pageNum, totalPages } = this.data;
    // 如果当前页已是最后一页，不再加载
    if (pageNum >= totalPages) return;
  
    const nextPage = pageNum + 1;
    const { targetType, targetId } = this.properties;
    const { pageSize, likedCommentIds, comments } = this.data;
  
    api.comment.getCommentList(nextPage, pageSize, {
      targetType: targetType,
      targetId: targetId
    }).then(res => {
      const newComments = res.records || res.list || [];
      // 匹配本地点赞状态
      const newCommentsWithLike = newComments.map(comment => ({
        ...comment,
        like: likedCommentIds.includes(comment.id)
      }));
      // 合并旧评论和新评论
      this.setData({
        comments: [...comments, ...newCommentsWithLike],
        pageNum: nextPage,
        totalPages: res.pages || totalPages // 假设接口返回总页数pages
      });
    }).catch(err => {
      console.error('加载更多评论失败：', err);
    });
  },
})
  